from whiff import resolver
from whiff import whiffenv
from whiff.middleware import misc

expectList = """
Protoerozoic
Ordovician
Triassic
Cretaceous
Paleogene
Neogene
""".split()

testJson = "[%s]" % (",".join(['"%s"'%x for x in expectList]))

def badPlace(name, weight="bold"):
    return """
    (function() {
        var elt = document.getElementById("%s");
        elt.style.fontWeight = "%s";
    }) ();
    """ % (name, weight)

def goodPlace(name):
    return badPlace(name, "normal");

def checkOrder(order):
    L = []
    lastindex = -1
    error = False
    for name in order:
        thisindex = expectList.index(name)
        if thisindex>lastindex:
            feedback = goodPlace(name)
        else:
            error = True
            feedback = badPlace(name)
        lastindex = thisindex
        L.append(feedback)
    if not error:
        L.append("message('right!');")
    else:
        L.append("message('periods in bold should be earlier');");
    return "\n".join(L)

class __middleware__(misc.utility):
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        orderStr = whiffenv.cgiGet(env, "order", testJson)
        #orderStr = testJson
        #pr "order is", testJson
        orderStr = resolver.unquote(orderStr)
        order = self.param_json(orderStr, env)
        #pr "parsed order is", order
        feedbacks = checkOrder(order)
        #pr "sending feedbacks"
        #pr feedbacks
        return self.deliver_page(feedbacks, env, start_response, "application/javascript")

if __name__=="__main__":
    app = __middleware__()
    env = {}
    result = app(env, misc.ignore)
    print list(result)
